package com.lg.order.producer.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lg.order.producer.config.MyMQConfig;
import com.lg.order.producer.utils.IdWorker;
import com.lg.order.producer.utils.PageUtils;
import com.lg.order.producer.utils.Query;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.lg.order.producer.dao.MessageDao;
import com.lg.order.producer.entity.MessageEntity;
import com.lg.order.producer.service.MessageService;


@Service("messageService")
public class MessageServiceImpl extends ServiceImpl<MessageDao, MessageEntity> implements MessageService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private IdWorker idWorker;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MessageEntity> page = this.page(
                new Query<MessageEntity>().getPage(params),
                new QueryWrapper<MessageEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void send() {
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setMessageId(String.valueOf(idWorker.nextId()));
        messageEntity.setClassType("string");
        messageEntity.setContent("rabbitmq 的分布式事务最终一致性解决方案");
        messageEntity.setMessageStatus(0);
        messageEntity.setCreateTime(new Date());
        messageEntity.setRoutingKey(MyMQConfig.DISTRIBUTED_TRANSACTION_KEY);
        messageEntity.setToExchane(MyMQConfig.DISTRIBUTED_TRANSACTION_EVENT_EXCHANGE);

        //String exchange, String routingKey, Object object)
        rabbitTemplate.convertAndSend(MyMQConfig.DISTRIBUTED_TRANSACTION_EVENT_EXCHANGE, MyMQConfig.DISTRIBUTED_TRANSACTION_KEY, messageEntity);

    }

    @Override
    public List<MessageEntity> selectByMessageStatusNo1() {
        return messageDao.selectByMessageStatusNo1();
    }

    public static void main(String[] args) {
        IdWorker idWorker = new IdWorker(1, 1, 1);
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setMessageId(String.valueOf(idWorker.nextId()));
        messageEntity.setClassType("string");
        messageEntity.setContent("rabbitmq 的分布式事务最终一致性解决方案");
        messageEntity.setMessageStatus(0);
        messageEntity.setCreateTime(new Date());
        messageEntity.setRoutingKey(MyMQConfig.DISTRIBUTED_TRANSACTION_KEY);
        messageEntity.setToExchane(MyMQConfig.DISTRIBUTED_TRANSACTION_EVENT_EXCHANGE);

        System.out.println(JSONObject.toJSONString(messageEntity));
    }
}